﻿using AutoMapper;
using Mes.Infrastructure.Data.BoundedContext.Repositories.WorkOrders;
using Mes.Domain.BoundedContext;
using Mes.Application.DTO.Inputs.WorkOrders;
using Mes.Application.DTO.Results.WorkOrders;
using Microsoft.EntityFrameworkCore;
using Mes.Application.Common;
using Mes.Application.Common.Resource;

namespace Mes.Application.Services.WorkOrders
{
    public class JobStateService : IJobStateService
    {
        private readonly IMapper _mapper;
        private readonly IJobStateRepository _job_StateRepository;

        public JobStateService(IMapper mapper, IJobStateRepository job_StateRepository)
        {
            if (mapper == null || job_StateRepository == null)
            {
                throw new ArgumentNullException();
            }
            _mapper = mapper;
            _job_StateRepository = job_StateRepository;
        }

        /// <summary>
        /// 更新作业状态
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="CustomException"></exception>
        public async Task UpdateJobStateAsync(UpdateJobStateInput input)
        {
            var job_State = await _job_StateRepository.FindAsync(x => x.State_Cd == input.State_Cd);
            if (job_State == null)
            {
                throw new CustomException(Messages.JobStateNotFound);
            }
            job_State.State_Desc = input.State_Desc;
            int status = await _job_StateRepository.SaveAsync();
            if (status <= 0)
            {
                throw new CustomException(Messages.ErrorSavingOper);
            }
        }

        /// <summary>
        /// 查询作业状态
        /// </summary>
        /// <returns>ItemsResult<JobStatesResult></returns>
        public async Task<ItemsResult<JobStatesResult>> GetAllJobStateAsync()
        {
            var job_States = await _job_StateRepository.Query().OrderBy(x=>x.State_Cd).ToListAsync();
            var data = _mapper.Map<List<JobStatesResult>>(job_States);
            var result=new ItemsResult<JobStatesResult> { Items= data };
            return result;
        }

    }
}
